import Immutable from 'immutable';
import { routerRedux } from 'dva/router';
import { addInsuranceInfo, hasInsuranceInfo, getWillInfo, updateWillInfo } from '../services/insurance';
import toast from '../utils/toast';
import { get, save } from '../utils/storage';

export default {
  namespace: 'insurance',
  state: Immutable.fromJS({
    showAddInfo: false,
    showWill: false,
  }),

  effects: {
    *fetchHasInfo({ payload }, { call, put }) {
      const res = yield call(hasInsuranceInfo, payload);
      if (res.success) {
        yield put({
          type: 'updateShowAddInfo',
          payload: res.data,
        });
      }
    },
    *addInsuranceInfo({ payload }, { call, put }) {
      const res = yield call(addInsuranceInfo, payload);
      if (res.success) {
        toast('登记成功');
        yield put(routerRedux.push('useableCouponList'));
      }
    },
    *fetchShowWill({ payload }, { call, put }) {
      const res = yield call(getWillInfo, payload);
      let isShow = false;
      const showPageNum = get('showPageNum');
      if (showPageNum === 1) {
        isShow = false;//关闭引导页
      } else {
        isShow = res.data;
      }
      if (res.success) {
        console.log(isShow);
        save('WillInfo', res.data);
        yield put({
          type: 'updateShowWill',
          payload: true,
        });
      }
    },
    *updateWill({ payload }, { call, put }) {
      const res = yield call(updateWillInfo, payload);
      save('showPageNum', 1);
      if (payload.renewalIntention === 0) {
        const isShow = false;//关闭引导页
        yield put({
          type: 'updateShowWill',
          payload: isShow,
        });
      }
      if (res.success) {
        console.log('更新成功');
      }
    },
    *showPage({ payload }, { put }) {
      yield put({
        type: 'updateShowWill',
        payload: payload.show,
      });
    },
  },

  reducers: {
    updateShowAddInfo(state, { payload }) {
      save('showAddInfo', payload);
      return state.set('showAddInfo', payload);
    },
    updateShowWill(state, { payload }) {
      return state.set('showWill', payload);
    },
  },
};
